import 'dart:ui' as ui;

import 'package:decimal/decimal.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/text_input_format_utils.dart';
import 'package:kq_flutter_pad_widgets/resources/kq_pad_theme_colors.dart';
import 'package:kq_flutter_pad_widgets/widgets/textFiled/kq_pad_textfiled.dart';

/// 注塑机多段温度
class KqPadImmTemperatureViewExpo extends StatefulWidget {
  const KqPadImmTemperatureViewExpo(
      {super.key,
      this.data,
      this.isCanEdit = false,
      this.decimalPlaces = '0',
      this.lowerLimitValue,
      this.upperLimitValue,
      this.fontColor,
      this.fontSize,
      this.isMultilevelRedMarked,
      this.pathPartColors,
      this.rectPartColors,
      this.temperaturePartColors,
      this.valueCallback});

  /// 用逗号隔开的熔体温度
  final String? data;

  /// 保留位数
  final String? decimalPlaces;

  /// 下限值
  final double? lowerLimitValue;

  /// 上限值
  final double? upperLimitValue;

  /// 是否可编辑吗
  final bool isCanEdit;

  /// 字体颜色
  final Color? fontColor;

  /// 字体大小
  final double? fontSize;

  /// 变红
  final String? isMultilevelRedMarked;

  /// 路径图块颜色
  final List<Color>? pathPartColors;

  /// 矩形图块颜色
  final List<Color>? rectPartColors;

  /// 温度图块颜色
  final List<Color>? temperaturePartColors;

  final void Function(String data, int index)? valueCallback;

  @override
  State<StatefulWidget> createState() => KqPadImmTemperatureViewExpoState();
}

class KqPadImmTemperatureViewExpoState
    extends State<KqPadImmTemperatureViewExpo> {
  List<String> value = ['-'];
  List<String> isRed = [];
  int? focusIndex;

  @override
  void initState() {
    super.initState();
    if (widget.data != null) {
      value = widget.data!.split(',');
    }
    if (widget.isMultilevelRedMarked != null) {
      isRed = widget.isMultilevelRedMarked!.split(',');
    }
  }

  @override
  void didUpdateWidget(covariant KqPadImmTemperatureViewExpo oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.data != null) {
      value = widget.data!.split(',');
    } else {
      value = ['-'];
    }
    if (widget.isMultilevelRedMarked != null) {
      isRed = widget.isMultilevelRedMarked!.split(',');
    } else {
      isRed = [];
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      double width = constraints.maxWidth;
      // double height = constraints.maxHeight;
      return SizedBox(
        width: width,
        height: kIsWeb ? 36.dm : 22.dm,
        child: CustomPaint(
          painter: ImmTemperaturePainter(
              value: value,
              isCanEdit: widget.isCanEdit,
              fontColor: widget.fontColor,
              fontSize: widget.fontSize,
              pathPartColors: widget.pathPartColors,
              rectPartColors: widget.rectPartColors,
              temperaturePartColors: widget.temperaturePartColors),
          child: widget.isCanEdit
              ? Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Row(
                      children: tempTextField(width, kIsWeb ? 28.dm : 10.dm),
                    ),
                    Row(
                      children: renderLine(width, 1.dm),
                    )
                  ],
                )
              : null,
        ),
      );
    });
  }

  List<Widget> tempTextField(double maxWidth, double maxHeight) {
    List<Widget> widgets = [];
    double temperaturePartWidth =
        (maxWidth - 18.dm - 6.dm * (value.length + 1)) / (value.length);

    for (var i = 0; i < value.length; i++) {
      Color textColor = widget.fontColor ?? const Color(0xFF000000);
      if (isRed.length > i && isRed[i] == '1') {
        textColor = KqPadThemeColors.textRed;
      }
      widgets.add(Container(
        margin: EdgeInsets.only(
          left: i == 0 ? 19.dm : 8.dm,
          top: kIsWeb ? 2.dm : 1.dm,
        ),
        width: temperaturePartWidth - 2.dm,
        // color: Colors.red,
        height: maxHeight,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            SizedBox(
              width: 6.dm,
            ),
            Expanded(
                child: KqPadTextFiled(
              maxLines: 1,
              showShadow: false,
              useParentHeight: false,
              textColor: textColor,
              fontSize: widget.fontSize ?? 8.dm,
              textAlign: TextAlign.left,
              fixedHeight: maxHeight,
              newValue: Decimal.tryParse(value[i])
                  ?.round(scale: int.parse(widget.decimalPlaces!))
                  .toString(),
              inputFormatters: [
                widget.decimalPlaces == '0'
                    ? FilteringTextInputFormatter.allow(RegExp("[0-9]"))
                    : FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                FilteringTextInputFormatter.deny(RegExp(r'^\.+')), //不能小数点开头
                NumLengthInputFormatter(integerLength: 9, decimalLength: 2),
                if (widget.decimalPlaces != null && widget.decimalPlaces == '0')
                  ...TextInputFormatUtils.maxInter(
                      widget.upperLimitValue != null
                          ? widget.upperLimitValue!.toInt()
                          : 450,
                      min: 0),
                if (widget.decimalPlaces != null && widget.decimalPlaces != '0')
                  ...TextInputFormatUtils.limitMinAndMax(
                    widget.upperLimitValue ?? 450,
                    min: 0,
                  )
              ],
              onFocusChanged: (hasFocus) {
                if (hasFocus) {
                  setState(() {
                    focusIndex = i;
                  });
                } else {
                  setState(() {
                    focusIndex = -1;
                  });
                }
              },
              onChanged: (data) {
                value.replaceRange(i, i + 1, [data]);
                widget.valueCallback?.call(value.join(','), i);
              },
            )),
            SizedBox(
              width: 6.dm,
            ),
          ],
        ),
      ));
    }
    return widgets;
  }

  List<Widget> renderLine(double maxWidth, double maxHeight) {
    List<Widget> widgets = [];
    double temperaturePartWidth =
        (maxWidth - 18.dm - 6.dm * (value.length + 1)) / (value.length);
    for (var i = 0; i < value.length; i++) {
      widgets.add(Container(
        margin: EdgeInsets.only(
          left: i == 0 ? 19.dm : 8.dm,
          top: 1.dm,
        ),
        width: temperaturePartWidth - 2.dm,
        height: maxHeight,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            SizedBox(
              width: 6.dm,
            ),
            Expanded(
                child: Container(
              color: focusIndex != null && focusIndex == i
                  ? const Color(0xFF0B71FF)
                  : const Color(0xFF9A9A9A),
              height: 1,
            )),
            SizedBox(
              width: 6.dm,
            )
          ],
        ),
      ));
    }

    return widgets;
  }
}

class ImmTemperaturePainter extends CustomPainter {
  ImmTemperaturePainter(
      {required this.value,
      required this.isCanEdit,
      this.fontColor,
      this.fontSize,
      this.pathPartColors,
      this.rectPartColors,
      this.temperaturePartColors});

  final List<String> value;

  final bool isCanEdit;

  final Color? fontColor;

  final double? fontSize;

  final Paint gradientPaint = Paint()..style = PaintingStyle.fill;
  final Paint whitePaint = Paint()
    ..style = PaintingStyle.fill
    ..color = KqPadThemeColors.bgTransparent;

  /// 路径图块颜色
  final List<Color>? pathPartColors;

  /// 矩形图块颜色
  final List<Color>? rectPartColors;

  /// 温度图块颜色
  final List<Color>? temperaturePartColors;

  @override
  void paint(Canvas canvas, Size size) {
    double width = size.width;
    // double height = size.height;
    double temperaturePartWidth = (width - 18.dm - 6.dm * (value.length + 1)) /
        (value.length); // 每段温度的宽度(动态),高度写死
    List<double> temperaturePartCenterDxList = [];

    // 喷口
    Path path1 = Path();
    path1.moveTo(0, 8.dm);
    path1.lineTo(0, kIsWeb ? 28.dm : 14.dm);
    path1.lineTo(kIsWeb ? 10.dm : 10.dm, kIsWeb ? 32.dm : 17.dm);
    path1.lineTo(kIsWeb ? 18.dm : 18.dm, kIsWeb ? 32.dm : 17.dm);
    path1.lineTo(kIsWeb ? 18.dm : 18.dm, kIsWeb ? 4.dm : 5.dm);
    path1.lineTo(kIsWeb ? 10.dm : 10.dm, kIsWeb ? 4.dm : 5.dm);
    path1.close();
    _drawPathPart(canvas, Offset(0, 8.dm),
        Offset(kIsWeb ? 22.dm : 18.dm, kIsWeb ? 32.dm : 24.dm), path1);

    // 温度段
    for (int i = 0; i < value.length; i++) {
      double startDx = 18.dm + (temperaturePartWidth * i) + 6.dm * i;
      double endDx = startDx + temperaturePartWidth;
      _drawTemperaturePart(canvas, Offset(startDx, 0),
          Offset(endDx, kIsWeb ? 36.dm : 22.dm), value[i]);
      temperaturePartCenterDxList.add(startDx + (temperaturePartWidth / 2));
      _drawRRectPart(canvas, Offset(endDx, 5.dm),
          Offset(endDx + 6.dm, kIsWeb ? 28.dm : 17.dm), 1.dm);
    }

    // 底部文本
    // for (int i = 0; i < value.length; i++) {
    //   _drawBottomText(
    //       canvas,
    //       temperaturePartCenterDxList[i],
    //       height,
    //       (i + 1).toString() + KqPadIntl.currentResource.segment,
    //       temperaturePartWidth);
    // }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }

  /// 绘制路径图块
  _drawPathPart(Canvas canvas, Offset from, Offset to, Path path) {
    _setPaintShader(
        gradientPaint,
        from,
        to,
        pathPartColors ??
            [
              const Color(0xFFCCCCCC),
              const Color(0xFFCCCCCC),
              const Color(0xFFCCCCCC)
            ]);
    canvas.drawPath(path, gradientPaint);
  }

  /// 绘制矩形图块
  _drawRRectPart(Canvas canvas, Offset from, Offset to, double radius) {
    _setPaintShader(
        gradientPaint,
        from,
        to,
        rectPartColors ??
            [
              const Color(0xFFCCCCCC),
              const Color(0xFFCCCCCC),
              const Color(0xFFCCCCCC)
            ]);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(from, to), Radius.circular(radius)),
        gradientPaint);
  }

  /// 绘制每段温度块
  _drawTemperaturePart(Canvas canvas, Offset from, Offset to, String text) {
    _setPaintShader(
        gradientPaint,
        from,
        to,
        temperaturePartColors ??
            [
              const Color(0xFFF2F2F2),
              const Color(0xFFE6E6E6),
              const Color(0xFFB3B3B3),
            ]);
// const Color(0xFFE3E3E3),
//       const Color(0xFFE6E6E6),
//       const Color(0xFFB3B3B3),

    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(from, to), Radius.circular(2.dm)),
        gradientPaint);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(Offset(from.dx + 5.dm, from.dy + 5.dm),
                Offset(to.dx - 5.dm, to.dy - 5.dm)),
            Radius.circular(1.dm)),
        whitePaint);
    if (!isCanEdit) {
      TextPainter textPainter = TextPainter(
          text: TextSpan(
              text: text.isNotEmpty
                  ? Decimal.tryParse(text)?.round().toString()
                  : '-',
              style: TextStyle(
                  fontSize: fontSize ?? 6.dm,
                  color: fontColor ?? const Color(0xFFFFFFFF),
                  fontWeight: FontWeight.w500)),
          textDirection: TextDirection.ltr)
        ..layout(minWidth: 0, maxWidth: to.dx - from.dx - 12.dm);
      Offset center = Offset(
          from.dx + ((to.dx - from.dx) / 2), from.dy + ((to.dy - from.dy) / 2));
      Offset textStart = Offset(center.dx - (textPainter.size.width / 2),
          center.dy - (textPainter.size.height / 2));
      textPainter.paint(canvas, textStart);
    }
  }

  /// 绘制底部文本
  // _drawBottomText(Canvas canvas, double centerDx, double parentHeight,
  //     String text, double maxWidth) {
  //   TextPainter textPainter = TextPainter(
  //       text: TextSpan(
  //           text: text,
  //           style: TextStyle(fontSize: 6.dm, color: const Color(0xFF262626))),
  //       textDirection: TextDirection.ltr)
  //     ..layout(minWidth: 0, maxWidth: maxWidth);
  //   Offset textStart = Offset(centerDx - (textPainter.size.width / 2),
  //       parentHeight - textPainter.size.height / 4);
  //   textPainter.paint(canvas, textStart);
  // }

  /// 设置画笔shader
  _setPaintShader(Paint paint, Offset from, Offset to, List<Color> color) {
    paint.shader = ui.Gradient.linear(
      from,
      Offset(from.dx, to.dy), // dx相同，渐变才会是垂直的
      color,
      const <double>[0, 0.5, 1.0],
    );
  }
}
